package com.keyin.android.net;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.net.Uri;

public class Param {
	
	private ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>();

	private HashMap<String, String> map = new HashMap<String, String>();

	public Param() {
	}

	public Param append(String key, String value) {
		return append(key, value, null);
	}

	public Param append(String key, String value, String encoding) {
		if (encoding != null && !encoding.equals("")) {
			value = Uri.encode(value);
		}
		map.put(key, value);
		return this;
	}

	public Param append(Param param) {
		HashMap<String, String> paramMap = param.toMap();

		Iterator<Entry<String, String>> iter = paramMap.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<String, String> entry = iter.next();
			String key = (String) entry.getKey();
			String val = (String) entry.getValue();

			map.put(key, val);
		}

		return this;
	}
	
	public ArrayList<NameValuePair> toList(){
		ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>();
		
		Iterator<Entry<String, String>> iter = map.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<String, String> entry = iter.next();	
			String key = (String) entry.getKey();
			String val = (String) entry.getValue();
			fields.add(new BasicNameValuePair(key, val));
		}
		
		Collections.sort(fields, new Comparator<NameValuePair>() {

			@Override
			public int compare(NameValuePair object1, NameValuePair object2) {
				String key1 = object1.getName();
				String key2 = object2.getName();
				return key1.compareTo(key2);
			}
		});
		
		return fields;
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		
		List<NameValuePair> list = toList();
		
		for (NameValuePair nv : list){
			String key = nv.getName();
			String val = nv.getValue();

			sb.append(key + "=" + val + "&");
		}

		return sb.toString();
	}

	public HashMap<String, String> toMap() {
		return map;
	}
}
